package com.lmx.persistence.service;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.HttpRequestUtil;
import com.lmx.common.util.PropertiesFileUtil;
import com.lmx.common.util.XMLUtil;
import com.lmx.repoDomain.tmodel.Call;
import com.lmx.repoDomain.tmodel.ImsPool;
import com.lmx.repoDomain.tmodel.Task;
import com.lmx.repoDomain.tmodel.UserTask;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import java.io.StringReader;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by qin on 2016/8/25.
 */
@Service
public class HuaweiService {
    private Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    protected GenericService dslJpaService;
    @PersistenceContext
    private EntityManager em;


    /**
     * 登录获取 Base token
     */
    public String login(String username,String password){
        logger.debug("管理员登录华为开始");
        username = "+" + username;
        logger.debug("username : " + username);
        logger.debug("password : " + password);
        String baseToken = "";
//        Properties properties = PropertiesFileUtil.getProperties("application.properties");
//        String username = properties.getProperty("huawei.loginName");
//        String password = properties.getProperty("huawei.password");
//        String username = "+8659522946022";
//        String password = "HUAWEIims_2";
        //第一次登录
        String str = HttpRequestUtil.sendHuaweiAuth("Digest username=\"" + username + "\",algorithm=MD5");
        logger.debug("第一次登录返回");
        String nonce = str.substring(str.indexOf("Digest nonce=\"") + 14,str.indexOf("\", realm=\""));
        String realm = str.substring(str.indexOf("\", realm=\"") + 10,str.indexOf("\", auth-name=\""));
        String authName = str.substring(str.indexOf("\", auth-name=\"") + 14,str.length()-1);
        String ha1 = CommonUtil.stringMD5(authName + ":" + realm + ":" + password);
        String ha2 = CommonUtil.stringMD5("POST:/login/sc");
        String response = CommonUtil.stringMD5(ha1 + ":" + nonce + ":" + ha2);
        String sec = "Digest " +
                "username=\"" + authName + "\",realm=\"" + realm + "\",nonce=\"" + nonce +
                "\",uri=\"/login/sc\",response=\"" + response + "\"";
        //第二次登录
        String resultXml = HttpRequestUtil.sendHuaweiAuth(sec);
        if(resultXml.startsWith("null")){
            resultXml = resultXml.substring(4);
        }
        baseToken = "Basic " + parseGetToken(resultXml);
        ActionContextHolder.setBaseTokenHolder(baseToken);
        logger.debug("管理员登录华为获取Base token ：" + baseToken);
        return baseToken;
    }

    /**
     * URLEncoding
     */
    public String URLEncoding(String str){
        try{
            str = java.net.URLEncoder.encode(str,   "utf-8");
        }catch (Exception e){
            logger.debug(e.toString());
        }
        return  str;
    }

    /**
     * 解析xml获取token
     * @param protocolXML
     * @return
     */
    public static String parseGetToken(String protocolXML) {
        String token = "";
        try {
            SAXParserFactory saxfac = SAXParserFactory.newInstance();
            SAXParser saxparser = saxfac.newSAXParser();
            TestSAX   tsax = new TestSAX();
            saxparser.parse(new InputSource(new StringReader(protocolXML)),tsax);
            token = tsax.getToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 下载录音
     */
    public void downloadRecord(String agentNumber,String recordFolder,String recordFileName,String relativePath){
//        String token = login();
        Call call = ActionContextHolder.getCallHolder().get(agentNumber);
        Task task = this.em.find(Task.class,call.getTask().getId());
        String username = task.getImsPool().getIms();
        String password = task.getImsPool().getImsPasswd();
        String token = login(username,password);
        HttpRequestUtil.downloadRecordfile(token, URLEncoding(recordFolder), URLEncoding(recordFileName), relativePath);
    }

    /**
     * SHA passwd
     * @param Passwd
     * @return
     */
    public String sha1Encrypt(String Passwd) {
        MessageDigest alg;
        byte[] bts = null;
        try {
            alg = MessageDigest.getInstance("SHA-1");
            alg.update(Passwd.getBytes());
            bts = alg.digest();
        }catch (Exception e){
            logger.debug(e.toString());
        }
        String result = "";
        String tmp = "";
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] &
                    0xFF));
            if (tmp.length() == 1) result += "0";
            result += tmp;
        }
        return result;
    }

    /**
     * 获取postData
     * @return
     */
    public String getPostData(Map head,Map body){
        String postData = "";
        postData += "<Request>\n";
        String headXML = XMLUtil.converter(head).replaceAll("<xml>", "<Head>").replaceAll("</xml>","</Head>");
        String bodyXML = XMLUtil.converter(body).replaceAll("<xml>", "<Body>").replaceAll("</xml>","</Body>");
        postData = postData + headXML + "\n" + bodyXML + "\n";
        postData += "</Request>";
        return postData;
    }

    /**
     * 新增任务总机
     * @param taskId
     */
    public boolean addTaskIms(Long taskId){
        boolean flag = false;
        if(addCorp(taskId)){
            if(addAgentgroup(taskId)){
                flag = true;
                logger.debug("任务总机添加成功！");
                return flag;
            }
        }
        logger.debug("任务总机添加失败！");
        return flag;
    }

    /**
     * 释放ims号码
     * @param taskId
     */
    public boolean releaseIms(Long taskId){
        boolean flag = false;
        List<UserTask> list = this.em.createQuery("select u from UserTask u where u.task.id = ?1")
                .setParameter(1,taskId)
                .getResultList();
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getImsPool() != null){
                delOperator(list.get(i).getId());//删除操作员
            }
        }
        delAgentgroup(taskId);//删除选线组
//        delCorp(taskId);//删除企业总机
        if(delCorp(taskId)){
            flag = true;
            logger.debug("释放ims成功");
        }
        return flag;
    }

    /**
     * 新增企业（绑定热线号码）
     */
    public boolean addCorp(Long taskId){
        boolean flag = false;
        String cropId = taskId.toString();
        Task task = this.em.find(Task.class,taskId);
        logger.debug("task status : " + task.getStatus().getId());
        String methdodName = "IPCC_ADD_CORP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupid = properties.getProperty("huawei.groupid");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        ImsPool imsPool = getImsUsableIsBuy();
        if(imsPool != null){
        	logger.debug("imsUse:" + imsPool.getIms());
            body.put("Ims", imsPool.getIms());
            body.put("Key", imsPool.getImsKey());
            body.put("CorpId",cropId);
            body.put("GroupId", groupid);
            String postData = getPostData(head,body);
            logger.debug("postData : " + postData);
            String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
            logger.debug("resXML : " + resXML);
            String resCode = getResCode(resXML);
            if("0".equals(resCode)){
                if(!pythonBindIms(imsPool)){
                    logger.debug("python 绑定总机失败");
                    task.setRemark("python 绑定总机失败,请查看，ims：" + imsPool.getIms());
                }
                imsPool.setStatus((short) ICommonConstants.IMSSTATUS.NOTUSABLE.ordinal());
                dslJpaService.setEntityClass(ImsPool.class);
                dslJpaService.update(imsPool);
                task.setImsPool(imsPool);
                dslJpaService.setEntityClass(Task.class);
                dslJpaService.update(task);
//                this.em.createQuery("update Ims i set i.status = ?1 where i.id = ?2")
//                        .setParameter(1, (short) ICommonConstants.IMSSTATUS.NOTUSABLE.ordinal())
//                        .setParameter(2,ims.getId())
//                        .executeUpdate();
//                this.em.createQuery("update Task t set t.ims.id = ?1 where t.id = ?2")
//                        .setParameter(1, ims.getId())
//                        .setParameter(2,taskId)
//                        .executeUpdate();
                flag = true;
                logger.debug("华为接口：新增企业（绑定热线号码）");
            }else {
//                this.em.createQuery("update Task t set t.remark = ?1 where t.id = ?2")
//                        .setParameter(1,"华为接口：新增企业（绑定热线号码）失败,请手工添加！resXML:" + resXML)
//                        .setParameter(2,taskId)
//                        .executeUpdate();
                task.setRemark("华为接口：新增企业（绑定热线号码）失败,请手工添加！resXML:" + resXML);
                dslJpaService.setEntityClass(Task.class);
                dslJpaService.update(task);
                logger.debug("华为接口：新增企业（绑定热线号码）失败");
            }
        }
        return flag;
    }

    /**
     * 删除企业（绑定热线号码）
     */
    public boolean delCorp(Long taskId){
        boolean flag = false;
        String cropId = taskId.toString();
        Task task = this.em.find(Task.class,taskId);
        String methdodName = "IPCC_RMV_CORP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupid = properties.getProperty("huawei.groupid");
//        String groupid = "99612";

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        ImsPool imsPool = task.getImsPool();
        logger.debug("imsUse:" + imsPool.getIms());
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        body.put("CorpId",cropId);
//        body.put("GroupId",groupid);
        String postData = getPostData(head,body);
        logger.debug("postData : " + postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug("resXML" + resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            imsPool.setStatus((short) ICommonConstants.IMSSTATUS.USABLE.ordinal());
            dslJpaService.setEntityClass(ImsPool.class);
            dslJpaService.update(imsPool);
            task.setImsPool(null);
            dslJpaService.setEntityClass(Task.class);
            dslJpaService.update(task);
            flag = true;
            logger.debug("华为接口：删除企业（绑定热线号码） taskId : " + taskId);
        }else {
            task.setRemark("华为接口：删除企业（绑定热线号码）失败,请手工删除！resXML:" + resXML);
            dslJpaService.setEntityClass(Task.class);
            dslJpaService.update(task);
            logger.debug("华为接口：删除企业（绑定热线号码）失败");
        }
        return flag;
    }

    /**
     * 新增选线组
     */
    public boolean addAgentgroup(Long taskId){
        boolean flag = false;
        String cropId = taskId.toString();
        String methdodName = "IPCC_ADD_AGENTGROUP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupName = properties.getProperty("huawei.groupname");
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupName",groupName);
        String postData = getPostData(head,body);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            flag = true;
            logger.debug("华为接口：新增选线组");
        }else {
            logger.debug("华为接口：新增选线组失败");
        }

        return flag;
    }

    /**
     * 删除选线组
     */
    public boolean delAgentgroup(Long taskId){
        boolean flag = false;
        String cropId = taskId.toString();
        String methdodName = "IPCC_RMV_AGENTGROUP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupName = properties.getProperty("huawei.groupname");
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupName",groupName);
        String postData = getPostData(head,body);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug("resXML:"+resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            flag = true;
            logger.debug("华为接口：删除选线组");
        }else {
            logger.debug("华为接口：删除选线组失败");
        }

        return flag;
    }

    /**
     * 新增操作员
     */
    public boolean addOperator(Long userTaskId){
        logger.debug("开始新增操作员");
        boolean flag = false;
        UserTask userTask = this.em.find(UserTask.class,userTaskId);
        String cropId = userTask.getTask().getId().toString();
        String methdodName = "IPCC_ADD_OPERATOR";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupid = properties.getProperty("huawei.groupid");
        String groupName = properties.getProperty("huawei.groupname");
        String operatorpasswd = properties.getProperty("huawei.operatorpasswd");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupId",groupid);
        body.put("GroupName",groupName);
        ImsPool imsPool = getImsUsable();
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        String cxd = 1000 + (imsPool.getId()%1000) + "";//四位短号  debugTest
        body.put("Cxd",cxd);
        body.put("OperatorPasswd",CommonUtil.MD5Encode(cxd + "@" + cropId + ":" + cropId + ":" + operatorpasswd,"utf-8"));
        String postData = getPostData(head,body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            imsPool.setStatus((short) ICommonConstants.IMSSTATUS.NOTUSABLE.ordinal());
            dslJpaService.setEntityClass(ImsPool.class);
            dslJpaService.update(imsPool);
            userTask.setImsPool(imsPool);
            userTask.setPhoneNumber("+" + imsPool.getIms());
            userTask.setPhonePassword(imsPool.getImsPasswd());
            userTask.setAgentNumber(cxd);
            userTask.setAgentPassword(operatorpasswd);
            dslJpaService.setEntityClass(UserTask.class);
            dslJpaService.update(userTask);
            flag = true;
            logger.debug("华为接口：新增操作员");
        }else {
            userTask.setRemark("华为接口：新增操作员失败，请手动添加，resXML：" + resXML);
            dslJpaService.setEntityClass(UserTask.class);
            dslJpaService.update(userTask);
            logger.debug("华为接口：新增操作员失败");

        }

        return flag;
    }

    /**
     * 删除操作员
     */
    public boolean delOperator(Long userTaskId){
        boolean flag = false;
        UserTask userTask = this.em.find(UserTask.class,userTaskId);
        String cropId = userTask.getTask().getId().toString();
        String methdodName = "IPCC_RMV_OPERATOR";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String groupid = properties.getProperty("huawei.groupid");
//        String groupid = "99612";
        String groupName = properties.getProperty("huawei.groupname");
//        String operatorpasswd = properties.getProperty("huawei.operatorpasswd");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
//        body.put("GroupId",groupid);
        body.put("GroupName",groupName);
        ImsPool imsPool = userTask.getImsPool();
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        String cxd = 1000 + (imsPool.getId()%1000) + "";//四位短号  debugTest
        body.put("Cxd",cxd);
//        body.put("OperatorPasswd",CommonUtil.MD5Encode(cxd + "@" + cropId + ":" + cropId + ":" + operatorpasswd,"utf-8"));
        String postData = getPostData(head,body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            imsPool.setStatus((short) ICommonConstants.IMSSTATUS.USABLE.ordinal());
            dslJpaService.setEntityClass(ImsPool.class);
            dslJpaService.update(imsPool);
            userTask.setImsPool(null);
            userTask.setPhoneNumber(null);
            userTask.setPhonePassword(null);
            userTask.setAgentNumber(null);
            userTask.setAgentPassword(null);
            dslJpaService.setEntityClass(UserTask.class);
            dslJpaService.update(userTask);
            flag = true;
            logger.debug("华为接口：删除操作员 userTaskId" + userTask.getId());
        }else {
            userTask.setRemark("华为接口：删除操作员失败，请手动删除，resXML：" + resXML);
            dslJpaService.setEntityClass(UserTask.class);
            dslJpaService.update(userTask);
            logger.debug("华为接口：删除操作员失败");
        }

        return flag;
    }

    /**
     * 获取当前时间
     * @return
     */
    public String getTimestamp(){
        Date date = new Date();
        SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateStr = sim.format(date);
        return dateStr;
    }

    /**
     * 获取单个可用号码(普通未订购套餐)
     */
    public ImsPool getImsUsable(){
        ImsPool imsPool = null;
        List result = this.em.createQuery("select i from ImsPool i where i.statusIms = ?1 and i.status = ?2 and i.isBuy = ?3")
                .setParameter(1,(short)ICommonConstants.IMSSTATUSHUAWEI.INUSE.ordinal())
                .setParameter(2,(short)ICommonConstants.IMSSTATUS.USABLE.ordinal())
                .setParameter(3,(short)ICommonConstants.IMSISBUY.FALSE.ordinal())
                .setMaxResults(1)
                .getResultList();
        if(result.size()>0){
            imsPool = (ImsPool) result.get(0);
        }
        return imsPool;
    }

    /**
     * 获取单个可用号码(总机已订购套餐)
     */
    public ImsPool getImsUsableIsBuy(){
        ImsPool imsPool = null;
        List result = this.em.createQuery("select i from ImsPool i where i.statusIms = ?1 and i.status = ?2 and i.isBuy = ?3")
                .setParameter(1,(short)ICommonConstants.IMSSTATUSHUAWEI.INUSE.ordinal())
                .setParameter(2,(short)ICommonConstants.IMSSTATUS.USABLE.ordinal())
                .setParameter(3,(short)ICommonConstants.IMSISBUY.TRUE.ordinal())
                .setMaxResults(1)
                .getResultList();
        if(result.size()>0){
        	imsPool = (ImsPool) result.get(0);
        }
        return imsPool;
    }

    /**
     * python 总机绑定事件
     * @param imsPool
     * @return
     */
    public boolean pythonBindIms(ImsPool imsPool){
        boolean flag = false;
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String bindUrl = properties.getProperty("call.bindurl");
        String content = "phoneNumber="+CommonUtil.URLEncoding("+" + imsPool.getIms())+"&phonePassword=" + imsPool.getImsPasswd();
        String result = HttpRequestUtil.sendGet(bindUrl,content);
        logger.debug(result);
        String code = null;
        if(result != null && !"".equals(result)){
            JSONObject jsonObject = JSONObject.fromObject(result);
            code = jsonObject.get("code").toString();
        }
        if("0".equals(code)){
            flag = true;
        }
        return flag;
    }

    /**
     * 获取返回值 code
     */
    public String getResCode(String resXML){
        Document dd = null;
        String resCode=null;
        try {
            dd = DocumentHelper.parseText(resXML);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return "";
            }
            Element result = root.element("Head").element("Result");
            if (result == null) {
                return "";
            }
            resCode = result.getText();  //解析 xml 获得 resCode
        }
        logger.debug("resCode:" + resCode);
        return resCode;
    }

    /**
     * 查询号码池
     */
    public void lstIms(){
        String methdodName = "LST_IMS";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");

        String authenticator = sha1Encrypt(methdodName + getTimestamp() + spid + passwd);
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        head.put("Authenticator",authenticator);
        Map<String,String> body = new HashMap<>();
        body.put("Status","1");
        String postData = getPostData(head, body);
        System.out.println(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        System.out.println(resXML);


        String phone = "";
        try {
            SAXParserFactory saxfac = SAXParserFactory.newInstance();
            SAXParser saxparser = saxfac.newSAXParser();
            TestSAX   tsax = new TestSAX();
            saxparser.parse(new InputSource(new StringReader(resXML)),tsax);
            phone = tsax.getPhone();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(phone);

    }

    /**
     * 注册号码
     */
    public void imsFast(){
        boolean flag = false;
        String methdodName = "IMS_FAST_FINISH";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");

        String authenticator = sha1Encrypt(methdodName + getTimestamp() + spid + passwd);
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        head.put("Authenticator",authenticator);
        Map<String,String> body = new HashMap<>();
//        body.put("AreaCode","591");
        body.put("IsPhone","0");
        String postData = getPostData(head, body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
    }

    /**
     * 注册号码(测试环境)
     */
    public ImsPool imsFastTest(){
        boolean flag = false;
        String methdodName = "IMS_FAST_FINISH";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");

        String authenticator = sha1Encrypt(methdodName + getTimestamp() + spid + passwd);
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        head.put("Authenticator",authenticator);
        Map<String,String> body = new HashMap<>();
        body.put("IsPhone","0");
        String postData = getPostData(head, body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        Document dd = null;
        String imsNum=null;
        String key = null;
        try {
            dd = DocumentHelper.parseText(resXML);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return null;
            }
            Element imsNumRes = root.element("Body").element("Ims");
            Element keyRes = root.element("Body").element("Key");
            if (imsNumRes == null || keyRes == null) {
                return null;
            }
            imsNum = imsNumRes.getText();
            key = keyRes.getText();
        }
        ImsPool imsPool = new ImsPool();
        imsPool.setIms(imsNum);
        imsPool.setImsKey(key);
        dslJpaService.setEntityClass(ImsPool.class);
        imsPool = (ImsPool)dslJpaService.create(imsPool);
        return imsPool;

    }

    /**
     * 测试环境获取密码(SDK)
     */
    public void abilityAdd(ImsPool imsPool){
        boolean flag = false;
        String methdodName = "ABILITY_ADD";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");

//        String authenticator = sha1Encrypt(methdodName + getTimestamp() + spid + passwd);
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
//        head.put("Authenticator",authenticator);
        Map<String,String> body = new HashMap<>();
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        body.put("Type","SDK");
        String postData = getPostData(head, body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        Document dd = null;
        String pwd=null;
        try {
            dd = DocumentHelper.parseText(resXML);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return ;
            }
            Element pwdRes = root.element("Body").element("Pwd");
            if (pwdRes == null ) {
                return ;
            }
            pwd = pwdRes.getText();
        }
        imsPool.setImsPasswd(pwd);
        imsPool.setStatusIms((short) 1);
        imsPool.setStatus((short) 0);
        imsPool.setIsBuy((short)0);
        dslJpaService.setEntityClass(ImsPool.class);
        dslJpaService.create(imsPool);

    }

    /**
     * 号码订购套餐
     */
    @Transactional
    public boolean imsBuy(ImsPool imsPool){
        boolean flag = false;
        String methdodName = "IMS_BUY";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
        String pointsSpId = properties.getProperty("huawei.pointsSpId");

        String authenticator = sha1Encrypt(methdodName + getTimestamp() + spid + passwd);
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        head.put("Authenticator",authenticator);
        Map<String,String> body = new HashMap<>();
        body.put("PointsSpId",pointsSpId);
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        body.put("Type","1");
        body.put("EffectType","1");
        String postData = getPostData(head, body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){

            this.em.createQuery("update Ims i set i.isBuy = ?1 where i.id = ?2")
                    .setParameter(1, (short) 1)
                    .setParameter(2, imsPool.getId())
                    .executeUpdate();
//            ims.setIsBuy((short)1);
//            this.em.merge(ims);
//            dslJpaService.setEntityClass(Ims.class);
//            dslJpaService.update(ims);
            flag = true;
        }
        logger.debug("华为接口：号码订购套餐");
        return flag;
    }


    /**
     * 新增企业（绑定热线号码）
     */
    public boolean addCorpByHand(String cropId){
        boolean flag = false;
//        String cropId = taskId.toString();
//        Task task = this.em.find(Task.class,taskId);
        String methdodName = "IPCC_ADD_CORP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huaweiTrue.spid");
        String appid = properties.getProperty("huaweiTrue.appid");
        String passwd = properties.getProperty("huaweiTrue.passwd");
        String url = properties.getProperty("huaweiTrue.ims.url");
        String groupid = properties.getProperty("huaweiTrue.groupid");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        ImsPool imsPool = getImsUsableIsBuy();
        if(imsPool != null){
        	logger.debug("imsUse:" + imsPool.getIms());
            body.put("Ims", imsPool.getIms());
            body.put("Key", imsPool.getImsKey());
            body.put("CorpId",cropId);
            body.put("GroupId",groupid);
            String postData = getPostData(head,body);
            String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
            String resCode = getResCode(resXML);
            if("0".equals(resCode)){

                imsPool.setStatus((short) ICommonConstants.IMSSTATUS.NOTUSABLE.ordinal());
                dslJpaService.setEntityClass(ImsPool.class);
                dslJpaService.update(imsPool);
                flag = true;
                logger.debug("华为接口：新增企业（绑定热线号码）");
            }else {
                logger.debug("华为接口：新增企业（绑定热线号码）失败");
            }

            logger.debug("-----------------------------------总机------------------------------------------");
            logger.debug("Ims : " + imsPool.getIms());
            logger.debug("Key : " + imsPool.getImsKey());
            logger.debug("ImsPasswd : " + imsPool.getImsPasswd());
            logger.debug("-----------------------------------总机------------------------------------------");
        }
        return flag;
    }

    /**
     * 新增选线组
     */
    public boolean addAgentgroupByHand(String cropId){
        boolean flag = false;
//        String cropId = taskId.toString();
        String methdodName = "IPCC_ADD_AGENTGROUP";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huaweiTrue.spid");
        String appid = properties.getProperty("huaweiTrue.appid");
        String passwd = properties.getProperty("huaweiTrue.passwd");
        String url = properties.getProperty("huaweiTrue.ims.url");
        String groupName = properties.getProperty("huaweiTrue.groupname");
        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupName",groupName);
        String postData = getPostData(head,body);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            flag = true;
            logger.debug("华为接口：新增选线组");
        }else {
            logger.debug("华为接口：新增选线组失败");
        }

        return flag;
    }

    /**
     * 新增操作员
     */
    public boolean addOperatorByHand(String cropId){
        boolean flag = false;
//        UserTask userTask = this.em.find(UserTask.class,userTaskId);
//        String cropId = userTask.getTask().getId().toString();
        String methdodName = "IPCC_ADD_OPERATOR";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huaweiTrue.spid");
        String appid = properties.getProperty("huaweiTrue.appid");
        String passwd = properties.getProperty("huaweiTrue.passwd");
        String url = properties.getProperty("huaweiTrue.ims.url");
        String groupid = properties.getProperty("huaweiTrue.groupid");
        String groupName = properties.getProperty("huaweiTrue.groupname");
        String operatorpasswd = properties.getProperty("huaweiTrue.operatorpasswd");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupId",groupid);
        body.put("GroupName",groupName);
        ImsPool imsPool = getImsUsable();
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
        String cxd = 1000 + (imsPool.getId()%1000) + "";//四位短号  debugTest
        body.put("Cxd",cxd);
        body.put("OperatorPasswd",CommonUtil.MD5Encode(cxd + "@" + cropId + ":" + cropId + ":" + operatorpasswd,"utf-8"));
        String postData = getPostData(head,body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            imsPool.setStatus((short) ICommonConstants.IMSSTATUS.NOTUSABLE.ordinal());
            dslJpaService.setEntityClass(ImsPool.class);
            dslJpaService.update(imsPool);
            flag = true;
            logger.debug("华为接口：新增操作员");
        }else {
            logger.debug("华为接口：新增操作员失败");
        }

        logger.debug("-----------------------------------操作员------------------------------------------");
        logger.debug("Ims : " + imsPool.getIms());
        logger.debug("Key : " + imsPool.getImsKey());
        logger.debug("ImsPasswd : " + imsPool.getImsPasswd());
        logger.debug("OperatorName : " + cxd);
        logger.debug("OperatorPasswd : " + operatorpasswd);
        logger.debug("-----------------------------------操作员------------------------------------------");

        return flag;
    }


    /**
     * 删除座席号码 debugTest
     */
    public boolean delAgentNum(String cropId,Long imsId,String groupid){
        boolean flag = false;
//        UserTask userTask = this.em.find(UserTask.class,userTaskId);
//        String cropId = userTask.getTask().getId().toString();
        String methdodName = "IPCC_RMV_AGENTNUM";
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String spid = properties.getProperty("huawei.spid");
        String appid = properties.getProperty("huawei.appid");
        String passwd = properties.getProperty("huawei.passwd");
        String url = properties.getProperty("huawei.ims.url");
//        String groupid = properties.getProperty("huawei.groupid");
        String groupName = properties.getProperty("huawei.groupname");
//        String operatorpasswd = properties.getProperty("huawei.operatorpasswd");

        Map<String,String> head = new HashMap<>();
        head.put("MethodName",methdodName);
        head.put("Spid",spid);
        head.put("Appid",appid);
        head.put("Passwd",sha1Encrypt(passwd));
        Map<String,String> body = new HashMap<>();
        body.put("CorpId",cropId);
        body.put("GroupId",groupid);
//        body.put("GroupId","99612");
//        body.put("GroupName",groupName);
        ImsPool imsPool = this.em.find(ImsPool.class,imsId);
        body.put("Ims", imsPool.getIms());
        body.put("Key", imsPool.getImsKey());
//        String cxd = 1000 + (imsPool.getId()%1000) + "";//四位短号  debugTest
//        body.put("Cxd",cxd);
//        body.put("OperatorPasswd",CommonUtil.MD5Encode(cxd + "@" + cropId + ":" + cropId + ":" + operatorpasswd,"utf-8"));
        String postData = getPostData(head,body);
        logger.debug(postData);
        String resXML = HttpRequestUtil.sendGet(url, "postData=" + CommonUtil.URLEncoding(postData));
        logger.debug(resXML);
        String resCode = getResCode(resXML);
        if("0".equals(resCode)){
            imsPool.setStatus((short) ICommonConstants.IMSSTATUS.USABLE.ordinal());
            dslJpaService.setEntityClass(ImsPool.class);
            dslJpaService.update(imsPool);
//            userTask.setImsPool(null);
//            userTask.setPhoneNumber(null);
//            userTask.setPhonePassword(null);
//            userTask.setAgentNumber(null);
//            userTask.setAgentPassword(null);
//            dslJpaService.setEntityClass(UserTask.class);
//            dslJpaService.update(userTask);
            flag = true;
            logger.debug("华为接口：删除座席号码");
        }else {
//            userTask.setRemark("华为接口：删除操作员失败，请手动删除，resXML：" + resXML);
//            dslJpaService.setEntityClass(UserTask.class);
//            dslJpaService.update(userTask);
            logger.debug("华为接口：删除座席号码失败");
        }

        return flag;
    }





}


/**
 * XML解析类
 */
class TestSAX extends DefaultHandler {
    private Log logger = LogFactory.getLog(this.getClass());

    private StringBuffer buf;
    private String str;
    private String token;
    private String phone;
    public TestSAX(){
        super();
    }

    public void startDocument() throws SAXException {
        buf=new StringBuffer();
        logger.debug("*******开始解析XML*******");
    }

    public void endDocument() throws SAXException{
        logger.debug("*******XML解析结束*******");
    }

    public void endElement(String namespaceURI,String localName,String fullName )throws SAXException{
        str = buf.toString();
        if("AccessToken".equals(fullName)){
            logger.debug("节点=" + fullName + "\tvalue=" + buf + " 长度=" + buf.length());
            token = str;
        }
        if("Ims".equals(fullName)){
            logger.debug("节点=" + fullName + "\tvalue=" + buf + " 长度=" + buf.length());
            phone = phone + str + "\n";
        }
        buf.delete(0,buf.length());
    }


    public void characters( char[] chars, int start, int length )throws SAXException{
        //将元素内容累加到StringBuffer中
        buf.append(chars,start,length);
    }

    public String getToken(){
        return token;
    }

    public String getPhone() {
        return phone;
    }
}